import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { getUserInfoAPI } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 1. 用来存储登录成功之后，得到的 token
    token: '', // 用户token
    userInfo: {} // 定义用户信息对象
  },
  getters: {
    username: (state) => state.userInfo.username,
    nickname: (state) => state.userInfo.nickname,
    user_pic: (state) => state.userInfo.user_pic
  },
  mutations: {
    // 更新 token 的 mutation 函数
    updateToken (state, newToken) {
      state.token = newToken
    },
    // 更新用户的信息
    updateUserInfo (state, info) {
      state.userInfo = info
    }
  },
  actions: {
    // 请求->用户信息
    async getUserInfoActions (store) {
      const res = await getUserInfoAPI()
      console.log(res)
      if (res.data.code === 0) {
        store.commit('updateUserInfo', res.data.data)
      }
    }
  },
  modules: {},
  // 配置为 vuex 的插件
  plugins: [createPersistedState()]
})
